package com.example.springssotestserver.controlelr;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_uri") String url, Model model,
                        @CookieValue(value = "sso_token", required = false) String token){
        if (!StringUtils.isEmpty(token)){
            return "redirect:"+url+"?token="+token;
        }
        model.addAttribute("url",url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLofin(String username,String password,String url,
    HttpServletResponse response){






        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            String token = UUID.randomUUID().toString().replace("-", "");
            System.out.println(username);
            System.out.println(password);
            Cookie sso_token = new Cookie("sso_token",token);
            response.addCookie(sso_token);

            return "redirect:"+url+"?token="+token;
        }
        // 登录成功指点的页面
        return "login";
    }
}
